package com.woniu.order.service.impl;

import cn.hutool.core.util.IdUtil;
import com.woniu.common.utils.UserUtil;
import com.woniu.order.dto.ApplyOrderDto;
import com.woniu.order.dto.DistributorDto;
import com.woniu.order.feign.ZfTraderFeign;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.common.utils.ResponseData;
import com.woniu.order.feign.ZfWorkFeign;
import com.woniu.order.pojo.*;
import com.woniu.order.service.*;
import com.woniu.order.mapper.ZfTraderorderaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author HP
 * @description 针对表【zf_traderordera(销售订单表，包含订单信息、销售员、价格、审批状态等信息)】的数据库操作Service实现
 * @createDate 2024-11-23 15:30:00
 */
@Service
public class ZfTraderorderaServiceImpl extends ServiceImpl<ZfTraderorderaMapper, ZfTraderordera>
        implements ZfTraderorderaService {
    @Autowired
    private ZfTraderFeign zfTraderFeign;
    @Autowired
    private ZfWorkFeign zfWorkFeign;
    @Autowired
    private ZfChanpinService zfChanpinService;
    @Autowired
    private ZfTraderorderaService zfTraderorderaService;
    @Autowired
    private ZfOrderService zfOrderService;
    @Autowired
    private ZfTraderdetailsService zfTraderdetailsService;
    @Autowired
    private ZfOrderhistoryProductService zfOrderhistoryProductService;

    @Override
    public ResponseData<?> applyOrder(ApplyOrderDto applyOrderDto) {
        // 1、通过flowable申请订单
        // 1.1、部署
        zfWorkFeign.deployProcess();

        // 1.2、启动
        // TODO:构建流程变量，预期放入redis中
        Map<String, Object> variables = new HashMap<>();
//        variables.put("saleMan", applyOrderDto.getSaleMan());
//        variables.put("orderNo", applyOrderDto.getOrderNo());
//        variables.put("companyPhone", applyOrderDto.getCompanyPhone());
//        variables.put("companyContact", applyOrderDto.getCompanyContact());
//        variables.put("validityEndDate", applyOrderDto.getValidityEndDate());
//        variables.put("distributorCode", applyOrderDto.getDistributorCode());
//        variables.put("discountRate", applyOrderDto.getDiscountRate());
//
//        applyOrderDto.getProductList().forEach(productDto -> {
//            variables.put("productCode" + productDto.getProductCode(), productDto.getProductCode());
//            variables.put("productName" + productDto.getProductName(), productDto.getProductName());
//        });

        // 启动流程
        zfWorkFeign.startProcess("orderApplication", variables);

        // 2、将申请订单写入订单申请表
        ZfOrder zfOrder = new ZfOrder();

        String orderNo = applyOrderDto.getOrderNo();
        String companyPhone = applyOrderDto.getCompanyPhone();
        String companyContact = applyOrderDto.getCompanyContact();//联系人
        String validityEndDate = applyOrderDto.getValidityEndDate();
        String saleMan = applyOrderDto.getSaleMan();
        String distributorCode = applyOrderDto.getDistributorCode();
        Double discountRate = applyOrderDto.getDiscountRate();//优惠率
        Double totalOriginalPrice = applyOrderDto.getTotalOriginalPrice();

        DistributorDto distributorDto = zfTraderFeign.queryByCode(distributorCode);
        String distributorName = distributorDto.getDistributorName();
        Integer id = distributorDto.getId();

        //申请人从jwt中取出
        String name = UserUtil.getUser("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjp" +
                "7ImlkIjoxLCJ1c2VybmFtZSI6IjEifX0.lfzDioYZlQ-cp_oJfo0XUMh70E1FvAvnUBGe-QgiFrs").getUsername();
        zfOrder.setCreatedBy(name);//申请人

        zfOrder.setDistributorId(id);
        zfOrder.setDistributorName(distributorName);
        zfOrder.setTotalPrice(BigDecimal.valueOf(totalOriginalPrice));

        //放到数据库里
        zfOrderService.save(zfOrder);

        // 3、再写入订单申请明细表
        ZfTraderdetails zfTraderdetails = new ZfTraderdetails();

        long orderId = IdUtil.getSnowflake(1, 1).nextId();

        zfTraderdetails.setCode(orderNo);
        zfTraderdetails.setDistributorName(distributorName);
        zfTraderdetails.setDistributorPhone(companyPhone);
        zfTraderdetails.setDistributorContact(companyContact);
        zfTraderdetails.setOrderDate(validityEndDate);
        zfTraderdetails.setSalesOrderCode(String.valueOf(orderId));
        zfTraderdetails.setSalesManager(saleMan);

        //用StringBuilder拼接所有产品名称
        StringBuilder allProductNames = new StringBuilder();
        // 使用 AtomicReference 来包装 BigDecimal
        AtomicReference<BigDecimal> totalPrice = new AtomicReference<>(BigDecimal.ZERO);

        applyOrderDto.getProductList().forEach(productDto -> {
            if (allProductNames.length() > 0) {
                allProductNames.append(",");//如果不是第一个产品，添加逗号分隔符
            }
            allProductNames.append(productDto.getProductName());

            //获取单价和数量
            Integer salesQuantity = productDto.getSalesQuantity();
            Double salePrice = productDto.getSalePrice();

            //计算
            if (salesQuantity != null && salePrice != null) {
                BigDecimal productTotalPrice = BigDecimal.valueOf(salePrice).multiply(BigDecimal.valueOf(salesQuantity));
                // 使用 AtomicReference 来累加到 totalPrice
                totalPrice.set(totalPrice.get().add(productTotalPrice));
            }
        });

        zfTraderdetails.setAllProductNames(allProductNames.toString());
        zfTraderdetails.setTotalOriginalPrice(totalPrice.get());

        //计算总折扣金额
        BigDecimal discountAmount = totalPrice.get().multiply(BigDecimal.valueOf(discountRate/100));
        zfTraderdetails.setDiscountAmount(discountAmount);

        zfTraderdetails.setOrderApplicant(saleMan);
        zfTraderdetails.setOrderStatus(0);

        //放到数据库
        zfTraderdetailsService.save(zfTraderdetails);

        List<ApplyOrderDto.ProductDto> productList = applyOrderDto.getProductList();

        //4、将集合里的物品和数量记录在库存数量
        productList.forEach(product -> {
            ZfOrderhistoryProduct zfOrderhistoryProduct = new ZfOrderhistoryProduct();

            String uuid = IdUtil.randomUUID();
            zfOrderhistoryProduct.setCode(uuid);

            zfOrderhistoryProduct.setProductCode(product.getProductCode());
            zfOrderhistoryProduct.setProductName(product.getProductName());
            zfOrderhistoryProduct.setNum(product.getSalesQuantity());
            zfOrderhistoryProduct.setProductPrice(BigDecimal.valueOf(product.getSalePrice()));
            zfOrderhistoryProduct.setApplyOrderCode(orderNo);

            //保存到数据库
            zfOrderhistoryProductService.save(zfOrderhistoryProduct);
        });

        //减库存（不该在这里）
//        zfChanpinService.reduce(productList);
        return new ResponseData<>().ok();
    }

    @Override
    public ResponseData<?> queryAllByTrader() {
        List<DistributorDto> distributorDtos = zfTraderFeign.queryAll();
        return new ResponseData<>().ok(distributorDtos);
    }

    @Override
    public ResponseData<?> queryByTraderCode(String code) {
        DistributorDto distributorDto = zfTraderFeign.queryByCode(code);
        long orderId = IdUtil.getSnowflake(1, 1).nextId();
        distributorDto.setOrderNo(String.valueOf(orderId));
        return new ResponseData<>().ok(distributorDto);
    }

    @Override
    public ResponseData<?> queryAllByProduct() {
        //查全部
        List<ZfChanpin> list = zfChanpinService.list();
        return new ResponseData<>().ok(list);
    }

    @Override
    public ResponseData<?> queryByProductCode(String code) {
        //根据code码查询
        ZfChanpin byId = zfChanpinService.getById(code);
        return new ResponseData<>().ok(byId);
    }
}




